<template>
  <view class="container">
    <!-- Logo 区域 -->
    <view class="logo-container">
      <image src="/static/images/logo.png" mode="aspectFit" class="logo"></image>
      <text class="app-name">农检通</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <u-form :model="form" ref="uForm" labelPosition="left" labelWidth="160rpx">
        <!-- 手机号 -->
        <u-form-item label="手机号码">
          <u-input v-model="form.phone" placeholder="请输入手机号码" />
        </u-form-item>

        <!-- 新密码 -->
        <u-form-item label="输入新密码">
          <u-input v-model="form.password" type="password" placeholder="6~12位数字或字母" />
        </u-form-item>

        <!-- 确认密码 -->
        <u-form-item label="确认新密码">
          <u-input v-model="form.confirmPassword" type="password" placeholder="请再次确认" />
        </u-form-item>

        <!-- 图形验证码 -->
        <u-form-item label="图形验证码">
          <view class="code-input">
            <u-input
              v-model="form.captcha"
              placeholder="请输入"
              maxlength="4"
            />
            <image
              :src="captchaUrl"
              @tap="refreshCaptcha"
              class="captcha-img"
              mode="aspectFit"
            />
          </view>
        </u-form-item>

        <!-- 提交按钮 -->
        <u-button
          type="success"
          @click="handleResetPassword"
          :loading="loading"
          style="width: 100%; margin-top: 60rpx;"
        >
          {{ loading ? '提交中...' : '确 认 重 置' }}
        </u-button>
      </u-form>
    </view>
  </view>
</template>

<script>
import {get, post } from '@/utils/request';
import md5 from 'blueimp-md5';

export default {
  data() {
    return {
      loading: false,
      captchaUrl: '', // 图形验证码图片（base64）
      uuid: '',       // 验证码唯一标识
      form: {
        phone: '',
        password: '',
        confirmPassword: '',
        captcha: ''     // 用户输入的图形验证码
      }
    };
  },
  mounted() {
    // 页面加载时获取图形验证码
    this.refreshCaptcha();
  },
  methods: {
    /**
     * 刷新图形验证码
     */
    async refreshCaptcha() {
      try {
        const res = await get('/captchaImage'); // 后端返回 { code: 200, uuid: '...', img: 'base64...' }
        if (res.code === 200) {
          this.uuid = res.uuid;
          this.captchaUrl = 'data:image/gif;base64,' + res.img;
        } else {
          uni.showToast({ title: res.msg || '获取图形验证码失败', icon: 'none' });
          // 失败后延迟重试
          setTimeout(() => this.refreshCaptcha(), 1500);
        }
      } catch (err) {
        console.error('获取图形验证码失败:', err);
        uni.showToast({ title: '网络异常，请重试', icon: 'none' });
        setTimeout(() => this.refreshCaptcha(), 1500);
      }
    },

    /**
     * 提交重置密码
     */
    async handleResetPassword() {
      const { phone, password, confirmPassword, captcha } = this.form;

      // 基础校验
      if (!phone || !password || !confirmPassword || !captcha) {
        uni.showToast({ title: '请填写全部信息', icon: 'none' });
        return;
      }

      if (!/^1[3-9]\d{9}$/.test(phone)) {
        uni.showToast({ title: '手机号格式错误', icon: 'none' });
        return;
      }

      if (password !== confirmPassword) {
        uni.showToast({ title: '两次密码不一致', icon: 'none' });
        return;
      }

      if (password.length < 6 || password.length > 12) {
        uni.showToast({ title: '密码长度为6~12位', icon: 'none' });
        return;
      }

      this.loading = true;
      try {
        const res = await post('/nongjt/userAuth/forgetPassword', {
          mobilePhone: phone,
          password: md5(password),     // 前端 MD5 加密
          captcha: captcha,           // 图形验证码
          uuid: this.uuid             // 验证码标识
        });

        if (res.code === 200) {
          uni.showToast({ title: '密码重置成功', icon: 'success' });
          setTimeout(() => {
            uni.navigateBack(); // 返回上一页（如登录页）
          }, 800);
        } else {
          uni.showToast({ title: res.msg || '重置失败', icon: 'none' });
          this.refreshCaptcha(); // 刷新验证码
          this.form.captcha = ''; // 清空输入
        }
      } catch (err) {
        console.error('重置密码请求异常:', err);
        uni.showToast({ title: err.msg || '请求失败，请检查网络', icon: 'none' });
        this.refreshCaptcha();
        this.form.captcha = '';
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
/* 复用注册页样式 */
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 80rpx 0;
  gap: 10rpx;
}

.logo {
  width: 160rpx;
  height: 160rpx;
}

.app-name {
  font-size: 40rpx;
  font-weight: bold;
  color: #3cc51f;
}

.form-container {
  width: 100%;
  max-width: 600rpx;
  padding: 0 30rpx;
}

.code-input {
  display: flex;
  align-items: center;
}

.code-input .u-input {
  flex: 1;
  margin-right: 20rpx;
}

.captcha-img {
  width: 160rpx;
  height: 80rpx;
  border-radius: 8rpx;
  border: 1px solid #ddd;
}
</style>